package com.mlh.springboot.config;

import com.mlh.springboot.bean.Car;
import com.mlh.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author 缪林辉
 * @date 2024/3/1 22:49
 * @DESCRIPTION
 */
//lite 模式下，直接返回新实例对象
@Configuration(proxyBeanMethods = false)
public class WebConfig {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        // 1.在addFormatters 方法中,增加一个自定义的转换器
        // 2.增加自定义转换器String -> Car
        // 3.增加的自定义转换器会注册到converters容器中
        // 4.converters 底层结构是ConcurrentHashMap内置有124转换器
        return new WebMvcConfigurer() {
            @Override
            public void addFormatters(FormatterRegistry registry) {
                registry.addConverter(new Converter<String, Car>() {
                    //这里就加入你的自定义的转换业务代码
                    @Override
                    public Car convert(String source) {
                        if(!ObjectUtils.isEmpty(source)){
                            Car car = new Car();
                            String[] split = source.split(",");
                            car.setName(split[0]);
                            car.setPrice(Double.parseDouble(split[1]));
                            return car;
                        }
                        return null;
                    }
                });
            }
        };
    }
    @Bean
    public WebMvcConfigurer addLoginInterceptor(){
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginInterceptor())
                        .addPathPatterns("/**")//拦截所有请求
                        .excludePathPatterns("/", "/login", "/images/**","/upload.html","/upload","/sql");//放行的请求, 可以根据需要增加
            }
        };
    }
}
